import Vue from 'vue'
import Vuex from 'vuex'
import {instance as api} from '@/common/ajax.js' // 全局挂载引入，配置相关在该index.js文件里修改

Vue.use(Vuex)

const auth = {
	/* 状态属性值 */
	state:()=>({
		user_detail:null,//用户所在地址及学校信息
	}),
	/* 计算属性 */
    getters: {},
    /* 计算方法 */
	mutations:{
		/** 登录
		 * @param {Object} state
		 * @param {Object} token
		 */
		LOGIN(state, token) {
			uni.setStorageSync('AccessToken',token.accessToken);
			uni.setStorageSync('RefreshToken',token.accessToken);
			uni.setStorageSync('Uid',token.userId);
		},
		/** 退出登录
		 * @param {Object} state
		 */
		LOGOUT(state) {
			uni.clearStorageSync('AccessToken');
			uni.clearStorageSync('RefreshToken');
			uni.clearStorageSync('Uid');
		},
		SET_USER_DETAIL(state,user_detail){
			state.user_detail=user_detail
		},
	},
	/*
		导步计算方法
		定义 incrementAsync  :function ({ commit, state,dispatch,rootState  },data){commit('increment',data)}
		使用 store.dispatch('incrementAsync', data) or  store.commit({type:'incrementAsync',...data})
	 */
	actions: {
		/** 检查是否登录
		 * @param {Object} state
		 */
		checkLogin({commit,state,dispatch},referrerId){
			let accessToken = uni.getStorageSync('AccessToken');
			if (!accessToken) {
				dispatch("login",referrerId);
			}else{
				api.post('/user/user_sign')
				uni.redirectTo({
					url:'/pages/index/index'
				})
			}
		},
		/**
		 * 登录
		 */
		login({commit,rootState,dispatch},referrerId){
			let that=this
			uni.login({
				success: (res) => {
					if(res.errMsg == 'login:ok'){
						that.code = res.code;
						//接下来访问接口
						let params={code:that.code}
						if(referrerId!=null){
							params.referrerId=referrerId
						}
						api.post('/auth/wxLogin', params).then(res => {
							if(res.code == 200){
								//更新根token								
								rootState.accessToken=res.data.accessToken
								rootState.refreshToken=res.data.accessToken
								rootState.uid=res.data.userId
								//提交登录
								commit('LOGIN', res.data)
								
								uni.redirectTo({
									url:'/pages/index/index'
								})
							}else{
								uni.showModal({
									content:res.msg
								})
							}
						}).catch(err => {
							let e = JSON.stringify(err);
							uni.showModal({
								content:e
							})
							console.log(err);
						})
						
					}else{
						uni.showToast({
							title:'系统异常，请联系管理员！'
						})
					}
				}
			})
		},
		//重置用户信息
		resetDetail({commit}){
			return new Promise((resolve,reject)=>{
				let uid = uni.getStorageSync('Uid');
				let now=new Date().getTime();
				api.post('/user/detail',{userId:uid}).then((res)=>{
					if (res.code == 200){
						let user_detail=res.data
						user_detail.expire=now+60*60*1000
						uni.setStorageSync('user_detail',user_detail);
						commit('SET_USER_DETAIL', user_detail)
						resolve()
					}else{
						reject()
					}
				})
			})
		},
	}
}

export default auth